package com.sywb.chuangyebao.utils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.bining.footstone.log.Logger;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;

/**
 * 分享工具类
 * Created by 55341 on 2018/2/1.
 */

public class ShareUtils {

    private static final int THUMB_SIZE = 60;

    public static final int SHARE_TYPE_WECHAT_FRIENDS = 0;
    public static final int SHARE_TYPE_WECHAT_FRIENDS_CIRCLE = 1;
    public static final int SHARE_TYPE_QQ_FRIENDS = 2;
    public static final int SHARE_TYPE_QQ_ZONE = 3;
    public static final int SHARE_TYPE_SINA = 4;

    public static void shareToWechat_webpage(final int type, final Activity mActivity, final String title, final String text, String image, final String url) {

        RequestOptions requestOptions = new RequestOptions();
        requestOptions.placeholder( R.mipmap.ic_launcher).error( R.mipmap.ic_launcher).fallback( R.mipmap.ic_launcher);

        Glide.with(mActivity).load(image).apply(requestOptions).into(new SimpleTarget<Drawable>() {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                shareToWechat(type,mActivity,title,text,url,resource);
            }

            @Override
            public void onLoadCleared(@Nullable Drawable placeholder) {
                super.onLoadCleared(placeholder);
                shareToWechat(type,mActivity,title,text,url,placeholder);
            }

            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                super.onLoadFailed(errorDrawable);
                shareToWechat(type,mActivity,title,text,url,errorDrawable);
            }
        });

//        if (TextUtils.isEmpty(image)) {
//            Bitmap bmp = BitmapFactory.decodeResource(mActivity.getResources(), R.mipmap.ic_launcher);
//            wechatLocalImage(type, mActivity, title, text, url);
//        } else {
//            wechatHttpImage(type, mActivity, title, text, image, url);
//        }
    }

    private static void shareToWechat(int type, Activity mActivity, String title, String text, String url, Drawable resource){

        if(mActivity.isFinishing()){
            return;
        }

        BitmapDrawable bd = (BitmapDrawable) resource;
        Bitmap bitmap= bd.getBitmap();

        Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, THUMB_SIZE, THUMB_SIZE, true);
        bitmap.recycle();

        WXWebpageObject webpageObject = new WXWebpageObject();
        webpageObject.webpageUrl = url;

        WXMediaMessage wxMediaMessage = new WXMediaMessage(webpageObject);
        wxMediaMessage.title = title;
        wxMediaMessage.description = text;
        wxMediaMessage.thumbData = bmpToByteArray(thumbBmp, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = wxMediaMessage;
        req.scene = type;

        IWXAPI iwxapi = WXAPIFactory.createWXAPI(mActivity, Constants.WEIXIN_APPID, false);
        iwxapi.registerApp(Constants.WEIXIN_APPID);
        iwxapi.sendReq(req);
    }

    private static byte[] bmpToByteArray(Bitmap bmp, boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    private static String buildTransaction(String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }


    public static void shareToQQ(Activity mActivity, String title, String text, String image, String url) {
        Tencent mTencent = Tencent.createInstance(Constants.QQ_APPID, mActivity);
        Bundle bundle = new Bundle();
        bundle.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
//这条分享消息被好友点击后的跳转URL。
        bundle.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url);
//分享的标题。注：PARAM_TITLE、PARAM_IMAGE_URL、PARAM_	SUMMARY不能全为空，最少必须有一个是有值的。
        bundle.putString(QQShare.SHARE_TO_QQ_TITLE, title);
//分享的图片URL
        bundle.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, image);
//分享的消息摘要，最长50个字
        bundle.putString(QQShare.SHARE_TO_QQ_SUMMARY, text);
//手Q客户端顶部，替换“返回”按钮文字，如果为空，用返回代替
        bundle.putString(QQShare.SHARE_TO_QQ_APP_NAME, mActivity.getString(R.string.app_name));
//标识该消息的来源应用，值为应用名称+AppId。
        bundle.putString(QQShare.SHARE_TO_QQ_EXT_INT, mActivity.getString(R.string.app_name) + Constants.QQ_APPID);

        mTencent.shareToQQ(mActivity, bundle, new IUiListener() {
            @Override
            public void onComplete(Object o) {

            }

            @Override
            public void onError(UiError uiError) {

            }

            @Override
            public void onCancel() {

            }
        });
    }


    public static void shareToQQZone(Activity mActivity, String title, String text, String image, String url) {
        Tencent mTencent = Tencent.createInstance(Constants.QQ_APPID, mActivity);
        Bundle bundle = new Bundle();
        bundle.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        bundle.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);//必填
        bundle.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, text);//选填
        bundle.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, url);//必填
        ArrayList<String> imgUrlList = new ArrayList<>();
        imgUrlList.add(image);
        bundle.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imgUrlList);
        mTencent.shareToQzone(mActivity, bundle, new IUiListener() {
            @Override
            public void onComplete(Object o) {

            }

            @Override
            public void onError(UiError uiError) {

            }

            @Override
            public void onCancel() {

            }
        });
    }


    public static void shareToSina(Activity mActivity, String title, String text, String image, String url) {
        //        // 设置ALL IN ONE分享按钮对应回调
//        Intent i = new Intent(mActivity, WBShareActivity.class);
//        i.putExtra(WBShareActivity.KEY_SHARE_TYPE, WBShareActivity.SHARE_ALL_IN_ONE);
//        mActivity.startActivity(i);

//        WbSdk.install(mActivity, new AuthInfo(mActivity, Constants.SINA_APPKEY, Constants.SINA_REDIRECT_URL, Constants.SINA_SCOPE));
//
//        // 注册到新浪微博
//        WbShareHandler shareHandler = new WbShareHandler(mActivity);
//        shareHandler.registerApp();
//
//        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
//        weiboMessage.textObject = getTextObj();
//        weiboMessage.imageObject = getImageObj();
////        weiboMessage.multiImageObject = getMultiImageObject();
////        weiboMessage.videoSourceObject = getVideoObject();
//        shareHandler.shareMessage(weiboMessage, false);


        SinaWeibo.ShareParams shareParams = new SinaWeibo.ShareParams();
        shareParams.setText(text + url);
        shareParams.setTitle(title);
        shareParams.setImageUrl(image);
        Platform platform = ShareSDK.getPlatform(SinaWeibo.NAME);
        platform.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Logger.e("新浪分享：onComplete");
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Logger.e("新浪分享：onError:" + throwable.getStackTrace().toString());
                Logger.e("新浪分享：onError:" + throwable.getMessage());
            }

            @Override
            public void onCancel(Platform platform, int i) {
                Logger.e("新浪分享：onCancel");
            }
        });
        platform.share(shareParams);

    }
}
